import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:hive/hive.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:gevbi/const_values.dart';
import 'package:gevbi/models/note_model.dart';
import 'package:gevbi/providers/change_view_style_provider.dart';
import 'package:gevbi/providers/theme_provider.dart';
import 'package:gevbi/screens/create_note_screen.dart';
import 'package:gevbi/screens/read_notes_screens.dart';
import 'package:gevbi/screens/settings_screen.dart';
import 'package:gevbi/utils/slide_transition.dart';
import 'package:provider/provider.dart';
import 'package:upgrader/upgrader.dart';
import 'dart:async';
import 'dart:io';
import 'package:flutter_zoom_drawer/flutter_zoom_drawer.dart';

class Home extends StatefulWidget {
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  Box<NoteModel>? storeData;

  Timer? timer;

  @override
  void initState() {
    super.initState();
    storeData = Hive.box<NoteModel>(noteBox);
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  void deleteDialog(key) {
    showDialog(
      context: context,
      builder: (_) {
        return Platform.isAndroid
            ? AlertDialog(
                title: Text('提示'),
                content: Text('确定删除该笔记?'),
                actions: <Widget>[
                  TextButton(
                    onPressed: () {
                      storeData!.delete(key);
                      Navigator.of(context).pop();
                      setState(() {});
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(),
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text(
                      '取消',
                      style: TextStyle(),
                    ),
                  )
                ],
              )
            : CupertinoAlertDialog(
                title: Text('提示'),
                content: Text('确定删除该笔记?'),
                actions: <Widget>[
                  TextButton(
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                    child: Text(
                      '取消',
                      style: TextStyle(),
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      storeData!.delete(key);
                      Navigator.of(context).pop();
                      setState(() {});
                    },
                    child: Text(
                      '确定',
                      style: TextStyle(),
                    ),
                  ),
                ],
              );
      },
    );
  }

  final _drawerController = ZoomDrawerController();
  bool _showDraw = false;
  @override
  Widget build(BuildContext context) {
    final checkTheme = Provider.of<ThemeProvider>(context);
    final homeViewStyle = Provider.of<ChangeViewStyleProvider>(context);
    Upgrader().clearSavedSettings();
    final config = AppcastConfiguration(
      url: appCast,
      supportedOS: ['android'],
    );
    return ZoomDrawer(
      controller: _drawerController,
      style: DrawerStyle.Style7,
      menuScreen: SettingsScreen(),
      mainScreen: Scaffold(
        appBar: AppBar(
          title: Text(
            '随心小记',
            style: TextStyle(
              color:
                  checkTheme.mTheme == false ? primaryColor : darkprimaryColor,
            ),
          ),
          leading: Builder(
            builder: (BuildContext context) {
              return IconButton(
                icon: Icon(
                  Icons.settings,
                ),
                onPressed: () {
                  setState(() {
                    ZoomDrawer.of(context)?.toggle();
                  });
                },
              );
            },
          ),
          actions: [
            IconButton(
              onPressed: () {
                homeViewStyle.checkButtonState();
              },
              icon: Icon(
                homeViewStyle.mChangeViewStyle == false
                    ? Icons.list
                    : Icons.grid_view_outlined,
              ),
            ),
            IconButton(
              onPressed: () {
                Navigator.of(context).pop();
                Navigator.of(context).push(MySlide(builder: (_) {
                  return CreateNoteScreen();
                }));
              },
              icon: Icon(
                CupertinoIcons.add,
              ),
            ),
          ],
        ),
        floatingActionButton: Platform.isAndroid
            ? FloatingActionButton(
                onPressed: () {
                  Navigator.of(context).pop();
                  Navigator.of(context).push(MySlide(builder: (_) {
                    return CreateNoteScreen();
                  }));
                },
                backgroundColor: Colors.white60,
                child: Icon(
                  Icons.add,
                ),
              )
            : null,
        body: UpgradeAlert(
          appcastConfig: config,
          debugLogging: true,
          countryCode: 'NG',
          dialogStyle: UpgradeDialogStyle.material,
          canDismissDialog: true,
          durationToAlertAgain: Duration(days: 1),
          child: storeData!.isEmpty
              ? Center(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/none.png',
                        color: checkTheme.mTheme == false
                            ? primaryColor
                            : darkprimaryColor,
                        width: 100,
                      ),
                      SizedBox(height: 10),
                      Text(
                        '暂无笔记',
                        style: TextStyle(
                          color: checkTheme.mTheme == false
                              ? primaryColor
                              : darkprimaryColor,
                          fontSize: 30,
                        ),
                      ),
                    ],
                  ),
                )
              : SingleChildScrollView(
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.0),
                    child: ValueListenableBuilder(
                      valueListenable: storeData!.listenable(),
                      builder: (context, Box<NoteModel> notes, _) {
                        List<int>? keys = notes.keys.cast<int>().toList();
                        return homeViewStyle.mChangeViewStyle == false
                            ? StaggeredGridView.countBuilder(
                                physics: NeverScrollableScrollPhysics(),
                                primary: false,
                                shrinkWrap: true,
                                crossAxisCount: 4,
                                mainAxisSpacing: 8.0,
                                crossAxisSpacing: 8.0,
                                addRepaintBoundaries: true,
                                itemBuilder: (_, index) {
                                  final key = keys[index];
                                  final NoteModel? note = notes.get(key);
                                  return GestureDetector(
                                    onTap: () {
                                      Navigator.of(context)
                                          .push(MySlide(builder: (_) {
                                        return ReadNotesScreen(
                                          note: note,
                                          noteKey: key,
                                        );
                                      }));
                                    },
                                    onLongPress: () {
                                      deleteDialog(key);
                                    },
                                    child: note!.title == null
                                        ? Container(
                                            decoration: BoxDecoration(
                                                color: Colors.white38,
                                                borderRadius: BorderRadius.all(
                                                    Radius.circular(10.0))),
                                            child: Padding(
                                              padding:
                                                  const EdgeInsets.all(16.0),
                                              child: Text(
                                                '${note.notes}',
                                                style: TextStyle(),
                                                softWrap: true,
                                              ),
                                            ),
                                          )
                                        : Container(
                                            decoration: BoxDecoration(
                                              color: checkTheme.mTheme == false
                                                  ? primaryColor.withOpacity(.3)
                                                  : darkprimaryColor
                                                      .withOpacity(.3),
                                              border: Border(
                                                top: BorderSide(
                                                  color:
                                                      checkTheme.mTheme == false
                                                          ? primaryColor
                                                          : darkprimaryColor,
                                                  width: 5,
                                                ),
                                              ),
                                            ),
                                            child: Padding(
                                              padding:
                                                  const EdgeInsets.all(9.0),
                                              child: Column(
                                                crossAxisAlignment:
                                                    CrossAxisAlignment.start,
                                                children: [
                                                  Text(
                                                    note.title == null ||
                                                            note.title == ''
                                                        ? '暂无笔记标题'
                                                        : '${note.title}',
                                                    softWrap: true,
                                                    style:
                                                        TextStyle(fontSize: 16),
                                                    textAlign: TextAlign.center,
                                                  ),
                                                  SizedBox(
                                                    height: 10,
                                                  ),
                                                  Expanded(
                                                    child: Text(
                                                      '${note.notes}',
                                                      style: TextStyle(
                                                        fontSize: 12,
                                                        fontFamily: 'sdf',
                                                        fontWeight:
                                                            FontWeight.w600,
                                                      ),
                                                      softWrap: true,
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ),
                                  );
                                },
                                itemCount: keys.length,
                                staggeredTileBuilder: (int index) =>
                                    StaggeredTile.count(
                                        2, index.isEven ? 2 : 1),
                              )
                            : ListView.builder(
                                physics: NeverScrollableScrollPhysics(),
                                primary: false,
                                shrinkWrap: true,
                                itemCount: keys.length,
                                itemBuilder: (context, index) {
                                  final key = keys[index];
                                  final NoteModel? note = notes.get(key);
                                  return GestureDetector(
                                    onTap: () {
                                      Navigator.of(context)
                                          .push(MySlide(builder: (_) {
                                        return ReadNotesScreen(
                                          note: note,
                                          noteKey: key,
                                        );
                                      }));
                                    },
                                    onLongPress: () {
                                      deleteDialog(key);
                                    },
                                    child: note!.title == null
                                        ? Column(
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                  color: Colors.white38,
                                                  border: Border(
                                                    left: BorderSide(
                                                      color: checkTheme
                                                                  .mTheme ==
                                                              false
                                                          ? primaryColor
                                                          : darkprimaryColor,
                                                      width: 5,
                                                    ),
                                                  ),
                                                ),
                                                child: ListTile(
                                                  title: Text(
                                                    '${note.notes}',
                                                    style: TextStyle(
                                                      fontSize: 20,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              SizedBox(
                                                height: 17,
                                              ),
                                            ],
                                          )
                                        : Column(
                                            children: [
                                              Container(
                                                decoration: BoxDecoration(
                                                  color:
                                                      checkTheme.mTheme == false
                                                          ? primaryColor
                                                              .withOpacity(.3)
                                                          : darkprimaryColor
                                                              .withOpacity(.3),
                                                  border: Border(
                                                    left: BorderSide(
                                                      color: checkTheme
                                                                  .mTheme ==
                                                              false
                                                          ? primaryColor
                                                          : darkprimaryColor,
                                                      width: 5,
                                                    ),
                                                  ),
                                                ),
                                                child: ListTile(
                                                  title: Text(
                                                    note.title == null ||
                                                            note.title == ''
                                                        ? '暂无笔记标题'
                                                        : '${note.title}',
                                                    style: TextStyle(
                                                      fontSize: 20,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              SizedBox(
                                                height: 17,
                                              ),
                                            ],
                                          ),
                                  );
                                },
                              );
                      },
                    ),
                  ),
                ),
        ),
      ),
    );
  }
}
